package com.project.workjob.controller;


import com.project.workjob.dto.ConfigDto;
import com.project.workjob.dto.HolidayDto;
import com.project.workjob.dto.WorkCalendarParam;
import com.project.workjob.entity.WorkCalendar;
import com.project.workjob.service.WorkCalendarService;
import com.project.workjob.util.HolidayHttpResult;
import com.project.workjob.util.HttpUtil;
import com.project.workjob.util.RestResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/workjob/calendar/")
public class WorkCalendarController {

    @Resource
    ConfigDto configDto;
    @Resource
    WorkCalendarService workCalendarService;

    @PostMapping("exec")
    public RestResult exec(@RequestBody WorkCalendarParam param) {
        try {
            workCalendarService.deleteByMonth(param);
            String url = configDto.getHolidayHost() + param.getMonth().replace("-", "");
            HttpUtil httpUtil = new HttpUtil(url, configDto.getTimeout());
            HolidayHttpResult result = httpUtil.getHolidayUrl();
            List<HolidayDto> holidayDtoList = result.getData().getList();
            if (holidayDtoList != null && holidayDtoList.size() > 0) {
                List<WorkCalendar> list = new ArrayList<>();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
                for (HolidayDto dto : holidayDtoList) {
                    WorkCalendar entity = new WorkCalendar();
                    entity.setCalendar_date(sdf.format(df.parse(dto.getDate())));
                    entity.setDate_name(dto.getWeek_cn());
                    entity.setFlag(dto.getWeek());
                    list.add(entity);
                }
                workCalendarService.insert(list);
            }
            return RestResult.ok();
        } catch (Exception e) {
            return RestResult.error(e.getMessage());
        }
    }
}
